#include "stdafx.h"
#include "Flac3dHook.h"

BOOL APIENTRY DllMain(HMODULE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		{
			//
			const int FIND_TRY_TIME = 50;
			CWindow hParentWnd,hFlac3dRootWnd;
			CWindow hEditParentWnd, hOutputWnd, hEditWnd;
			for (int i=0;i<FIND_TRY_TIME;++i)
			{
				::Sleep(100);
				//if (!m_Flac3dRootWnd)
				{
					hFlac3dRootWnd = ::FindWindowExW(NULL,NULL,L"Itasca2Manager",NULL);
					ATLASSERT(hFlac3dRootWnd != NULL);
					// ATLASSERT(m_Flac3dRootWnd!=NULL && ::IsWindow(m_Flac3dRootWnd));
				}
				if (!(hFlac3dRootWnd!=NULL && ::IsWindow(hFlac3dRootWnd)))
					continue;

				//
				//if (!parentWnd)
				{
					hParentWnd = 
						::FindWindowExW(
						::FindWindowExW(
						::FindWindowExW(hFlac3dRootWnd,NULL,L"Itasca2Client",NULL)
						,NULL,L"FLAC3D",L"Command Window"
						)
						,NULL,L"FLAC3D",L"FLAC3D"
						);
				}
				if (!hParentWnd)
					continue;

				//if (!editParentWnd)
				{
					hEditParentWnd = ::FindWindowExW(hParentWnd,NULL,L"FLAC3D",L"FLAC3D");
					ATLASSERT(hEditParentWnd!=NULL);
				}
				if (!hEditParentWnd)
					continue;


				hEditWnd = ::FindWindowExW(hEditParentWnd,NULL,L"Edit",NULL);
				if (hEditWnd)
				{
					hOutputWnd = ::FindWindowExW(hParentWnd,hEditParentWnd,L"FLAC3D",L"FLAC3D");
					ATLASSERT(hOutputWnd!=NULL);
					break;
				}
				else	// if (editWnd==NULL)
				{
					hOutputWnd = hEditParentWnd;
					hEditParentWnd = ::FindWindowExW(hParentWnd,hOutputWnd,L"FLAC3D",L"FLAC3D");
					hEditWnd = ::FindWindowExW(hEditParentWnd,NULL,L"Edit",NULL);
					ATLASSERT(hEditWnd!=NULL);
					if (hEditWnd)
						break;
					else
						continue;
				}
			}
			if (hEditWnd==NULL)
			{
				MessageBox(NULL,L"Failed to find FLAC3D command input window.",
					L"FLAC3D Hook",	MB_OK|MB_ICONERROR);
				return TRUE;
			}

			SubclassEditCtrl(hEditWnd, hModule);
		}
		break;
	case DLL_THREAD_ATTACH:
		break;
	case DLL_THREAD_DETACH:
		break;
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

